//
//  Home_Root_Controller.m
//  DaShiHuiHome
//
//  Created by apple on 16/2/17.
//  Copyright © 2016年 河南大实惠电子商务有限公司. All rights reserved.
//
#define kspace 8
#import "Home_Root_Controller.h"
#import "Home_Root_HeaderView.h"
#import "Home_Root_CollectionViewCell.h"
#import "Home_Root_ViewModel.h"
#import "Global.h"
#import "MTA.h"

//controllers
#import "BaiDuLocationViewController.h"
#import "Strort_Breakfas_Controller.h"
#import "SearchRootController.h"
#import "Strore_detailController.h"
#import "Home_goodList_Controller.h"
#import "Service_HomemakingController.h"
#import "Service_listController.h"
//untils
#import "UIColor+Hex.h"
#import "AppDelegate.h"
#import "UIImage+ColorToImage.h"
#import "NSString+TextSize.h"
#import "ManagerGlobeUntil.h"
#import "ManagerHttpBase.h"
#import "NSString+Conversion.h"
//vendor
#import "MJRefresh.h"
#import "FMDBManager.h"
#import "RDVTabBarController.h"
#import "RDVTabBarItem.h"
//model
#import "XiaoQuAndStoreInfoModel.h"
//view
#import "Home_TableView_SubjectViewCell.h"
#import "Home_TableView_ServiceViewCell.h"

@interface Home_Root_Controller ()<UICollectionViewDelegate,UICollectionViewDataSource,Home_Root_CollectionViewCellDelegate,Home_TableView_SubjectViewCellDelegate,Home_TableView_ServiceViewCellDelegate>
{
    NSInteger _requestPage;//当前请求页
    NSInteger _totalCount;//数据总条数
    CALayer     *layer;
}
@property(nonatomic, strong)Home_Root_HeaderView *collectionHeaderView;
@property(nonatomic, strong)Home_Root_ViewModel *viewModel;
@property (nonatomic,strong)UIButton *toTopbtn;//回到顶部按钮
@property (nonatomic,strong) UIBezierPath *path;// 动画路径
@property(nonatomic, strong)NSMutableArray *storeListArr;//商品列表

@property (nonatomic,strong) UIImage *goodImage;//商品图片
@property (nonatomic,strong)NSDictionary *dicData;
@property (nonatomic,strong)NSString *shopID;
@end

@implementation Home_Root_Controller

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setSubView];
    _requestPage = 1;
    _storeListArr = [[NSMutableArray alloc]init];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#efefef"];
    XiaoQuAndStoreInfoModel *model = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
     self.shopID =model.storeID;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    XiaoQuAndStoreInfoModel *model = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    [self setHomeNavgationTitleViewWithButtonTitle:model.storeName];
   
 
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        if (_shopID != model.storeID) {
            _requestPage =1;
            [self loadStoreListDataWithPage:1 requestCount:kRequestLimit];
            [self.collectionView setContentOffset:CGPointMake(0, 0) animated:YES];
        }else{
            if (_requestPage ==1) {
                [self loadStoreListDataWithPage:1 requestCount:kRequestLimit];
            }
        }
        [self.viewModel loadHomeHeaderDataSuccess:^(NSDictionary *responseData) {
            [self.collectionHeaderView updateTableViewWithData:responseData];
            [self.collectionView reloadData];
        } failue:^(bool isFailure) {
            
        }];
    }
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [MTA trackPageViewBegin:@"首页"];
    
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [MTA trackPageViewEnd:@"首页"];
    
}
#pragma mark -- request Data
- (void)loadStoreListDataWithPage:(NSInteger)page requestCount:(NSInteger)requestCount{
    //请求参数说明：
//    SIGNATURE				设备识别码
//    STOREID				店铺ID
//    PAGENUM				页码
//    PAGESIZE				数量
    [[ManagerGlobeUntil sharedManager]showHUDWithMsg:@"加载中..." inView:self.view];
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    ManagerHttpBase *manager = [ManagerHttpBase sharedManager];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    [parameter setObject:[NSString stringISNull:mode.storeID] forKey:@"STOREID"];
    [parameter setObject:[NSNumber numberWithInteger:page] forKey:@"PAGENUM"];
    [parameter setObject:[NSNumber numberWithInteger:requestCount] forKey:@"PAGESIZE"];
    __weak typeof(self)weakSelf = self;
    [manager parameters:parameter customPOST:@"goods/listByRecom" success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        [[ManagerGlobeUntil sharedManager] hideHUDFromeView:weakSelf.view];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dataDic = (NSDictionary*)responseObject;
            NSString *msg = [dataDic objectForKey:@"MSG"];
            NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
            if ([state isEqualToString:@"0"]) {//请求成功
                XiaoQuAndStoreInfoModel *xiaoQuModel =[[ManagerGlobeUntil sharedManager]getxiaoQuAndStoreInfo];
                _shopID =xiaoQuModel.storeID;
                _totalCount = [[NSString stringTransformObject:[[dataDic objectForKey:@"OBJECT"] objectForKey:@"TOTALROW"]] integerValue];
                if (_requestPage == 1) {//请求第一页清空数据
                    [weakSelf.storeListArr removeAllObjects];
                }
                [weakSelf.storeListArr addObjectsFromArray:[[dataDic objectForKey:@"OBJECT"] objectForKey:@"LIST"]];
                _collectionView.hidden=NO;
                
                if (_storeListArr.count == 0) {//如果数据为0隐藏返回顶部按钮
                    weakSelf.toTopbtn.hidden =YES;
                }
            }else {//请求失败
                if (msg.length == 0) {
                    msg = @"请求数据出现异常";
                }
                [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:msg inView:self.view];
                weakSelf.toTopbtn.hidden =YES;
                [weakSelf.storeListArr removeAllObjects];
            }
            [weakSelf.collectionView reloadData];
        }
        [weakSelf endRefresh];
        
    } failure:^(bool isFailure) {
        [[ManagerGlobeUntil sharedManager] hideHUDFromeView:self.view];
        [weakSelf endRefresh];
        [weakSelf.storeListArr removeAllObjects];
        [weakSelf.collectionView reloadData];
        weakSelf.toTopbtn.hidden =YES;
    }];
    
}
#pragma mark --buttonClick
-(void)toTopBtnClick
{
    [self.collectionView setContentOffset:CGPointMake(0, 0) animated:YES];
}
//搜索框跳转
- (void)beatSearchEvent:(id)sender {
    SearchRootController *searchRootVC = [[SearchRootController alloc]init];
    [self.navigationController pushViewController:searchRootVC animated:NO];
}
//选择区域
- (void)titleItemButtonAction:(id)sender {
    BaiDuLocationViewController*userLocation=[[BaiDuLocationViewController alloc]init];
    userLocation.suppperControllerType = kOther_ControllerSupperController;
    UINavigationController *naVc =[[UINavigationController alloc]initWithRootViewController:userLocation];
    [self presentViewController:naVc animated:YES completion:nil];
}
#pragma mark -- UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y > self.view.bounds.size.height) {
        self.toTopbtn.hidden = NO;
    } else {
        self.toTopbtn.hidden = YES;
    }
}
#pragma mark -- UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _storeListArr.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dataDic = [self.storeListArr objectAtIndex:indexPath.row];
    Home_Root_CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Home_CollectionViewCell" forIndexPath:indexPath];
    cell.indexPath =indexPath;
    cell.delegate =self;
    [cell.layer setBorderColor:[UIColor colorWithHexString:@"#dddddd"].CGColor];
    [cell.layer setBorderWidth:0.7];
    [cell retSubViewWithData:dataDic];
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) { // header
        UICollectionReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"Home_CollectionReusableView" forIndexPath:indexPath];
        
        
        [reusableView addSubview:self.collectionHeaderView];
        
        return reusableView;
    }
 
    return nil;
}
#pragma mark -- UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary *dataDic = [self.storeListArr objectAtIndex:indexPath.row];
    
    Strore_detailController *detailVc=[[Strore_detailController alloc]init];
    detailVc.goodsID =  [NSString stringTransformObject:[dataDic objectForKey:@"ID"]] ;
    detailVc.isSelf = [NSString stringTransformObject:[dataDic objectForKey:@"ISSELF"]];
    [self.navigationController pushViewController:detailVc animated:YES];
}
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *Cell = [self.collectionView cellForItemAtIndexPath:indexPath];
    Cell.alpha = 0.6;
    
}
- (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *Cell = [self.collectionView cellForItemAtIndexPath:indexPath];
    Cell.alpha = 1;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    
     return CGSizeMake(VIEW_WIDTH, [self.collectionHeaderView calculationFactHight]);
    
}
#pragma mark --Home_TableView_SubjectViewCellDelegate
- (void)selectedItemAtIndexPath:(NSIndexPath *)indexPath goodID:(NSString *)goodID isSelf:(NSString *)isSelf{
    Strore_detailController *detailVc=[[Strore_detailController alloc]init];
    detailVc.goodsID = goodID;
    detailVc.isSelf =isSelf;
    [self.navigationController pushViewController:detailVc animated:YES];
}
-(void)moreButtonSelectedWithListByTag:(NSString *)listTag listName:(NSString *)listName
{
    Home_goodList_Controller *goodListVc=[[Home_goodList_Controller alloc]init];
    goodListVc.listTag = listTag ;
    goodListVc.listName = listName;
    [self.navigationController pushViewController:goodListVc animated:YES];
}
#pragma mark -- Home_TableView_ServiceViewCellDelegate
-(void)selectedItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
        [appDelegate selectedControllerAtTabBarIndex:2];
    }else if(indexPath.row ==1){
        Service_listController *listVc=[[Service_listController alloc]init];
        listVc.code=@"07";
        listVc.titles=@"休闲娱乐";
        [self.navigationController pushViewController:listVc animated:YES];
    }else if(indexPath.row ==2)
    {
        Service_listController *listVc=[[Service_listController alloc]init];
        listVc.code=@"04";
        listVc.titles=@"洗衣";
        [self.navigationController pushViewController:listVc animated:YES];
        
    }
}
#pragma mark - 上拉/下拉  更新数据

-(void)headerRereshing {
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        _requestPage = 1;
        [self loadStoreListDataWithPage:_requestPage requestCount:kRequestLimit];
    } else {
        [self endRefresh];
    }
}
-(void)footerRereshing
{
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        if (_requestPage*kRequestLimit < _totalCount) {
            
            _requestPage++;
            [self loadStoreListDataWithPage:_requestPage requestCount:kRequestLimit];
        } else {
            
            [_collectionView setFooterRefreshingText:@"已加载完全部商品~"];
            
            
            [self endRefresh];
        }
        
    } else {
        [self endRefresh];
        
    }
    
}
- (void)endRefresh
{
    [self.collectionView headerEndRefreshing];
    [self.collectionView footerEndRefreshing];
}
#pragma mark --加入购物车
-(void)inToShopCarWithDic:(NSDictionary *)dicData
{
    
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    NSString *shopID=[NSString stringISNull:mode.storeID];
    NSString *goodID=[NSString stringTransformObject:[dicData objectForKey:@"ID"]];
    NSString *name =[NSString stringTransformObject:[dicData objectForKey:@"NAME"]];
    
    NSData *picture =UIImagePNGRepresentation(_goodImage);
    NSString *type=[NSString stringTransformObject:[dicData objectForKey:@"TYPE"]];
    NSString *price=[NSString stringWithFormat:@"%.2f",[[NSString stringTransformObject:[dicData objectForKey:@"SELLPRICE"]] floatValue]];
    NSString *oldprice=[NSString stringWithFormat:@"%.2f",[[NSString stringTransformObject:[dicData objectForKey:@"MARKETPRICE"]] floatValue]];
    NSString *ischoose =@"1";
    NSString *isProprietary =[NSString stringTransformObject:[dicData objectForKey:@"ISSELF"]];
    if ([isProprietary isEqualToString:@"1"]) {
        shopID =@"";
    }
    NSMutableDictionary *goodSqlite=[[FMDBManager sharedManager]QueryDataWithShopID:shopID goodID:goodID];
    if (goodSqlite.count ==0) { //购物车没数据 先存
        NSString *buynum= @"1";
        [[FMDBManager sharedManager]InsertWithshopID:shopID goodID:goodID name:name Picture:picture type:type price:price oldprice:oldprice buynum:buynum ischoose:ischoose isProprietary:isProprietary];
        
    }else{//购物车有数据 更新数据
        NSString *str=[goodSqlite objectForKey:@"buynum"];
        if ([isProprietary isEqualToString:@"1"])
        {
            [[FMDBManager sharedManager]deleteOneDataWithgoodID:goodID];
        }else{
            [[FMDBManager sharedManager]deleteOneDataWithShopID:shopID goodID:goodID];
        }
        //字符串 变数字 然后加减完 变回字符串
        NSInteger buynum =str.integerValue;
        buynum++;
        NSString *srr=[NSString stringWithFormat:@"%ld",(long)buynum];
        [[FMDBManager sharedManager]InsertWithshopID:shopID goodID:goodID name:name Picture:picture type:type price:price oldprice:oldprice buynum:srr ischoose:ischoose isProprietary:isProprietary];
    }
}
#pragma mark -- Strore_CollectionViewCellDelegate
-(void)selectedItemAtIndexPath:(NSIndexPath *)indexPath buttonPoint:(CGPoint)buttonPonint
{
    
    _dicData =[_storeListArr objectAtIndex:indexPath.row];
    _goodImage =[UIImage createImageWithImageUrlString:[NSString stringTransformObject:[_dicData objectForKey:@"THUMB"]]];
    if (_goodImage==nil) {
        _goodImage=[UIImage imageNamed:@"productDetail_Default"];
    }
    
    UICollectionViewCell *Cell = [self.collectionView cellForItemAtIndexPath:indexPath];
    CGPoint cellInSelfViewPoint = [[Cell superview] convertPoint:CGPointMake(Cell.frame.origin.x, Cell.frame.origin.y) toView:self.view];
    self.path = [UIBezierPath bezierPath];
    [_path moveToPoint:CGPointMake(cellInSelfViewPoint.x +buttonPonint.x+5, cellInSelfViewPoint.y +buttonPonint.y+5)];
    [_path addLineToPoint:CGPointMake(VIEW_WIDTH/10*7,VIEW_HEIGHT-49-64)];
    [self startAnimation];
    
    
}
#pragma mark--加入物品动画
-(void)startAnimation
{
    if (!layer) {
        
        layer = [CALayer layer];
        layer.contents = (__bridge id)_goodImage.CGImage;
        layer.contentsGravity = kCAGravityResizeAspectFill;
        layer.bounds = CGRectMake(0, 0,30, 30);
        [layer setCornerRadius:CGRectGetHeight([layer bounds]) / 2];
        layer.masksToBounds = YES;
        layer.position =CGPointMake(50, 150);
        [self.view.layer addSublayer:layer];
    }
    [self groupAnimation];
}
-(void)groupAnimation
{
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.path = _path.CGPath;
    animation.rotationMode = kCAAnimationRotateAuto;
    CABasicAnimation *narrowAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    narrowAnimation.beginTime = 0.3;
    narrowAnimation.fromValue = [NSNumber numberWithFloat:1.0f];
    narrowAnimation.duration = 0.6f;
    narrowAnimation.toValue = [NSNumber numberWithFloat:0.2f];
    
    narrowAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    CAAnimationGroup *groups = [CAAnimationGroup animation];
    groups.animations = @[animation,narrowAnimation];
    groups.duration = 0.8f;
    groups.removedOnCompletion=NO;
    groups.fillMode=kCAFillModeForwards;
    groups.delegate = self;
    [layer addAnimation:groups forKey:@"group"];
}

-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    //    [anim def];
    if (anim == [layer animationForKey:@"group"]) {
        
        [layer removeFromSuperlayer];
        layer = nil;
        //购物车按钮动画
        
        [self inToShopCarWithDic:_dicData];
        CABasicAnimation *shakeAnimation = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];
        shakeAnimation.duration = 0.3f;
        shakeAnimation.fromValue = [NSNumber numberWithFloat:-1.5];
        shakeAnimation.toValue = [NSNumber numberWithFloat:1.5];
        shakeAnimation.autoreverses = YES;
        AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
        RDVTabBarItem *tabBarItem = (RDVTabBarItem*)[appDelegate.tabBarController.tabBar.items objectAtIndex:3];
        [tabBarItem.layer addAnimation:shakeAnimation forKey:nil];
        
    }
    //    self.path = [UIBezierPath bezierPath];
    //    [_path moveToPoint:CGPointMake(50, 150)];
    //    [_path addQuadCurveToPoint:CGPointMake(270, 300) controlPoint:CGPointMake(150, 20)];
    //    
}
#pragma mark-- 初始化控件
-(void)setSubView
{
     [self.view addSubview:self.collectionView];
    _toTopbtn =[UIButton buttonWithType:UIButtonTypeCustom];
    _toTopbtn.hidden =YES;
    _toTopbtn.frame= CGRectMake(VIEW_WIDTH-70, VIEW_HEIGHT-64-49-60, 40, 40);
    [_toTopbtn setImage:[UIImage imageNamed:@"store_btn_back_top"] forState:UIControlStateNormal];
    [_toTopbtn addTarget:self action:@selector(toTopBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_toTopbtn];
}
#pragma mark -- 懒加载
- (Home_Root_HeaderView*)collectionHeaderView {
    if (!_collectionHeaderView) {
        Home_Root_HeaderView *headerView = [[Home_Root_HeaderView alloc]initWithFrame:CGRectZero delegate:self];
        headerView.backgroundColor = [UIColor clearColor];
        _collectionHeaderView = headerView;
    }
    return _collectionHeaderView;
}
- (UICollectionView*)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake(HightScalar(172), HightScalar(248));
        layout.sectionInset = UIEdgeInsetsMake(0, HightScalar(10), HightScalar(10), HightScalar(10));
        CGRect collectionViewFrame = CGRectMake(0, 0, self.view.bounds.size.width, VIEW_HEIGHT-49-64);
        UICollectionView *collectionview = [[UICollectionView alloc]initWithFrame:collectionViewFrame collectionViewLayout:layout];
        collectionview.backgroundColor = [UIColor whiteColor];
        [collectionview registerClass:[Home_Root_CollectionViewCell class] forCellWithReuseIdentifier:@"Home_CollectionViewCell"];
        [collectionview registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Home_CollectionReusableView"];
       
        //添加上拉加载更多
        [collectionview addHeaderWithTarget:self action:@selector(headerRereshing)];
        [collectionview addFooterWithTarget:self action:@selector(footerRereshing)];
        collectionview.delegate = self;
        collectionview.dataSource = self;
        collectionview.userInteractionEnabled = YES;
        _collectionView = collectionview;
    }
    return _collectionView;
}
- (Home_Root_ViewModel*)viewModel {
    if (!_viewModel) {
        Home_Root_ViewModel *viewmodel = [[Home_Root_ViewModel alloc]init];
        _viewModel = viewmodel;
    }
    return _viewModel;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
